import axios from 'axios';

// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL:  'http://niswnx.natappfree.cc',
  baseURL:  'http://localhost:8088',
  // 超时
  timeout: 10000,
  //默认请求头
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

// request拦截器
request.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    console.log('res: ', res);
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    //获取错误信息
    const msg = res.data.msg;
    if (code == '200') {
      return Promise.resolve(res.data);
    } else {
      return Promise.reject(msg);
    }
  },
  (error) => {
    console.log('err' + error);
    let { message } = error;
    if (message == 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    // ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
    return Promise.reject(error);
  },
);

export default request;
